import { setRouteChange } from '@/logics/mitt/routerChange';
import networkConfig from '@/config/modules/network';
import routerConfig from '@/config/modules/router';
import { AxiosCanceler } from '@/utils/http/axiosCancel';
import { warn } from '@/utils/log';
import { NotifyPlugin } from 'tdesign-vue-next';
import nProgress from 'nprogress';

// 不要更改创建顺序
export function setupRouterGuard(router) {
	createPageGuard(router);
	createPageLoadingGuard(router);
	createHttpGuard(router);
	createScrollGuard(router);
	createMessageGuard(router);
	createProgressGuard(router);
}

/**
 * 用于处理页状态的挂钩
 */
function createPageGuard(router) {
	const loadedPageMap = new Map();

	router.beforeEach(async (to) => {
		// 页面已经加载完毕，再次打开会更快，不需要进行加载等处理
		to.meta.loaded = !!loadedPageMap.get(to.path);
		// 通知路由更改
		setRouteChange(to);

		return true;
	});

	router.afterEach((to) => {
		loadedPageMap.set(to.path, true);
	});
}

// 用于处理页加载状态
function createPageLoadingGuard(router) {
	// const userStore = useUserStoreWithOut();
	// const appStore = useAppStoreWithOut();
	// const { getOpenPageLoading } = useTransitionSetting();
	// router.beforeEach(async (to) => {
	// 	if (!userStore.getToken) {
	// 		return true;
	// 	}
	// 	if (to.meta.loaded) {
	// 		return true;
	// 	}
	// 	if (unref(getOpenPageLoading)) {
	// 		appStore.setPageLoadingAction(true);
	// 		return true;
	// 	}
	// 	return true;
	// });
	// router.afterEach(async () => {
	// 	if (unref(getOpenPageLoading)) {
	// 		// TODO 寻找更好的方法
	// 		// 定时器模拟加载时间，防止闪烁过快，
	// 		setTimeout(() => {
	// 			appStore.setPageLoading(false);
	// 		}, 220);
	// 	}
	// 	return true;
	// });
}

/**
 * 切换路由时关闭当前页面以完成请求的接口
 * @param router
 */
function createHttpGuard(router) {
	const { removeAllHttpPending } = networkConfig;
	let axiosCanceler;
	if (removeAllHttpPending) {
		axiosCanceler = new AxiosCanceler();
	}
	router.beforeEach(async () => {
		// 切换路由将删除以前的请求
		axiosCanceler?.removeAllPending();
		return true;
	});
}

// 路由开关回到顶部
function createScrollGuard(router) {
	const isHash = (href) => {
		return /^#/.test(href);
	};

	const body = document.body;

	router.afterEach(async (to) => {
		// 滚到到顶部
		isHash(to?.href) && body.scrollTo(0, 0);
		return true;
	});
}

/**
 * 用于路由切换时关闭所有消息
 * @param router
 */
export function createMessageGuard(router) {
	const { closeMessageOnSwitch } = routerConfig;

	router.beforeEach(async () => {
		try {
			if (closeMessageOnSwitch) {
				NotifyPlugin.closeAll();
			}
		} catch (error) {
			warn('message guard error:' + error);
		}
		return true;
	});
}

export function createProgressGuard(router) {
	router.beforeEach(async (to) => {
		if (to.meta.loaded) {
			return true;
		}
		nProgress.start();
		return true;
	});

	router.afterEach(async () => {
		nProgress.done();
		return true;
	});
}
